#!/bin/bash

whoname=`whoami`
sudo chown ${whoname} /opt;


echo "scripts path: $(dirname $0)"
cd $(dirname $0);
if [[ $1 == "y" ]]; then
    echo "############# update scripts code #############";
    git config pull.rebase false;
    git reset --hard;
    git pull ;
    chmod -R 755 *;
    echo "############ update scripts code ##############";
fi;
echo "scripts list:";
echo -e "#########################################"
echo -e "\033[1m"
find * -type f -name pi.*.sh|sort|xargs echo -n >/tmp/scripts_list;
cat /tmp/scripts_list| awk -F' ' '{for(i=1;i<=NF;i++) print "* "i " --> ",$i"\n"}';

echo -e "\033[0m"
echo -e "#########################################"

echo "#########################################"
scripts_list=(`cat /tmp/scripts_list`);
list_sum=${#scripts_list[@]};
echo "list max number: `expr ${list_sum} `";
if [[ ${1} -le ${list_sum} ]] && [[ ${1} -gt 0 ]] && [[  "${1}" =~ ^[0-9]+$ ]]; then
    scripts_number=$1
else
    read -p "choice scripts number:" scripts_number;

fi;




app_number=`expr ${scripts_number} - 1`
echo "########### choice number: ${scripts_number} ##########"
if [[ ${scripts_number} -gt ${list_sum} ]] || [[ ${app_number} -lt 0 ]] ||[[ ! "${scripts_number}" =~ ^[0-9]+$ ]]; then
   echo -e "\033[1mnumber choice error;exit scripts !\033[0m"
   exit 127;
else


    echo "########## start ${scripts_list[${app_number}]} ##########"
	scritps_path=${scripts_list[${app_number}]%/*};
	echo "##### install_path: ${scritps_path} #####";
	cd ${scritps_path};chmod 755 *;
	scripts_name=${scripts_list[${app_number}]##*/};
    echo "##### begin ${scripts_name} #####";
	./${scripts_name} 
fi;
